package hwr.iamdr.Service;

import java.io.*;

import java.util.Date;
import java.util.logging.*;

import javax.servlet.http.*;
import javax.servlet.ServletException;

import org.apache.commons.lang3.StringEscapeUtils;

import com.google.appengine.api.datastore.*;
import com.google.appengine.api.datastore.Query.SortDirection;

import com.google.gson.*;
import com.google.gson.stream.JsonWriter;

@SuppressWarnings("serial")
public class ContentServlet extends HttpServlet
{
	static final DatastoreService dataStore	= DatastoreServiceFactory.getDatastoreService();
	static final Logger logger	= Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
	static final JsonParser parser	= new JsonParser();

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		Entity userEntity	= MainServlet.UserSession(req);
		if(userEntity == null)
		{
			resp.getWriter().write("Wrong user session");
			resp.setStatus(0);
			return;
		}

		if(req.getParameter("type").equals("Forum"))
		{
			BufferedReader reader	= req.getReader();
			JsonObject json	= parser.parse(reader).getAsJsonObject();

			Entity entity	= new Entity("Forum",userEntity.getKey());
			entity.setProperty("Topic",json.get("Topic").getAsString());
			entity.setProperty("Content",json.get("Content").getAsString());
			entity.setProperty("Date",new Date(System.currentTimeMillis()));
			Key key	= dataStore.put(entity);

			logger.log(Level.INFO,"ID : " + key.getId() + "{ " + json.toString() + " }");
		}
		else logger.log(Level.WARNING,"Not support " + req.getParameter("type") + " content type");
	}

	@Override
	protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
	{
		Entity userEntity	= MainServlet.UserSession(req);
		if(userEntity == null)
		{
			resp.getWriter().write("Wrong user session");
			resp.setStatus(0);
			return;
		}

		JsonWriter writer	= new JsonWriter(resp.getWriter());

		writer.beginObject();
		writer.name("User");
		writer.beginObject();
		writer.name("Name");
		writer.value((String)userEntity.getProperty("Name"));
		writer.endObject();

		int i	= 0;
		Query query	= new Query("Forum").addSort("Date",SortDirection.DESCENDING);
		for(Entity item : dataStore.prepare(query).asIterable(FetchOptions.Builder.withLimit(6)))
		{
			if(i == 0)
			{
				writer.name("Forum");
				writer.beginArray();
			}

			writer.beginObject();
			writer.name("Topic");
			writer.value(item.getProperty("Topic").toString());
			writer.name("Content");
			writer.value(StringEscapeUtils.escapeHtml4(item.getProperty("Content").toString()));
			writer.endObject();

			i++;
		}

		if(i > 0)
			writer.endArray();
		writer.endObject();
	}
}
